package org.swfer.UIC 
{
	import flash.display.DisplayObject;
	import flash.display.MovieClip;
	import flash.events.KeyboardEvent;
	import flash.events.MouseEvent;
	import flash.text.TextField;
	
	/**
	 * 输入文本框
	 * 必须部件 text:TextField
	 * 可选部件 placeholder
	 * 可选状态 focus=frame2
	 * @author swfer
	 */
	public class TextInput extends Component 
	{
		
		public function TextInput(view:MovieClip) 
		{
			super(view);
		}
		
		//////////////////////////////////////////
		/// method
		//////////////////////////////////////////
		
		override protected function addEvt():void
		{
			view.addEventListener(MouseEvent.MOUSE_DOWN, onFocus);
		}
		
		override protected function removeEvt():void
		{
			view.removeEventListener(MouseEvent.MOUSE_DOWN, onFocus);
			view.stage.removeEventListener(MouseEvent.MOUSE_DOWN, leaveFocus);
			view.stage.removeEventListener(KeyboardEvent.KEY_UP, onKeyUp);
		}
		
		override protected function init():void
		{
			(view['text'] as TextField).type = 'input';
			view['text'].text = '';
			
			if (placeholder && placeholder.hasOwnProperty('mouseEnabled'))
			{
				placeholder['mouseEnabled'] = false;
			}
		}
		
		//////////////////////////////////////////
		/// evt handlers
		//////////////////////////////////////////
		
		/**
		 * 点击控件任意位置，都使输入文本获得焦点。如果控件有焦点状态，则切换到焦点状态
		 */
		protected function onFocus(e:MouseEvent):void 
		{
			view.stage.addEventListener(MouseEvent.MOUSE_DOWN, leaveFocus);
			if (placeholder)
			{
				view.stage.addEventListener(KeyboardEvent.KEY_UP,onKeyUp);
			}
			
			view.stage.focus = view['text'];
			view['text'].text = view['text'].text;
			
			if (view.totalFrames >= 2)
			{
				view.gotoAndStop(2);
			}
		}
		
		/**
		 * 控件失去焦点时。回到默认视图状态
		 */
		protected function leaveFocus(e:MouseEvent):void 
		{
			if (view.hitTestPoint(e.stageX, e.stageY)) return;
			view.stage.removeEventListener(MouseEvent.MOUSE_DOWN, leaveFocus);
			view.stage.removeEventListener(KeyboardEvent.KEY_UP, onKeyUp);
			if (view.currentFrame != 1) view.gotoAndStop(1);
		}
		
		/**
		 * 按键弹起，检测是否有输入。如果输入为空并且存在占位符，则显示默认占位符。
		 */
		protected function onKeyUp(e:KeyboardEvent):void 
		{	
			if (placeholder)
			{
				placeholder.visible = !(view['text'].text) || view['text'].text == '\r';
			}
		}
		
		//////////////////////////////////////////
		/// getters/setters
		//////////////////////////////////////////
		
		public function get text():String {return view['text'].text;}
		public function set text(value:String):void 
		{
			view['text'].text = value;
		}
		
		/**
		 * 默认占位符
		 */
		public function get placeholder():DisplayObject
		{
			return view.getChildByName('placeholder');
		}
	}

}